<template>
  <div class="app-person">
    <div class="perbox">
      <h2>个人中心</h2>
      <div class="user-info">
        <div class="userbox">
          <div class="userphoto">
            <img src="../../../../assets/images/user/user2.png"
                 alt="" />
          </div>
          <div class="opinion">
            <div class="username">
              <div class="lfna">
                <div class="left">
                  <p>{{user.nickName}}</p>
                  <span>{{user.roleTypeName}}</span>
                </div>
                <el-button type="text"
                           @click="dialogFormVisible = true"
                           icon="el-icon-edit-outline">修改密码</el-button>
              </div>
              <div class="bottom">
                <p class="el-icon-phone-outline">
                  <span @click="dialogFormVisible2 = true">
                    {{user.phonenumber||'暂无绑定'}}
                  </span>
                </p>
                <p class="el-icon-message">
                  <span @click="dialogFormVisible3 = true">{{user.email||'暂无绑定'}}</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="botuser">
        <h3>员工信息</h3>
        <p>
          工作单位:
          <span>{{user.deptName}}</span>
        </p>
        <p>
          上级:
          <span>无</span>
        </p>
        <!-- 退出跳转到登录页 -->
        <el-button @click.native="logout">退出</el-button>
      </div>
    </div>

    <!-- 修改密码 -->
    <el-dialog title="修改密码"
               :visible.sync="dialogFormVisible"
               width="593px"
               height="376px">
      <el-form :model="ruleForm"
               status-icon
               :rules="rules"
               ref="ruleForm"
               class="demo-ruleForm">
        <el-form-item prop="oldPassword">
          <el-input type="password"
                    v-model="ruleForm.oldPassword"
                    autocomplete="off"
                    placeholder="请输入旧密码"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input type="password"
                    v-model="ruleForm.pass"
                    autocomplete="off"
                    placeholder="请输入新的密码"></el-input>
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input type="password"
                    v-model="ruleForm.checkPass"
                    autocomplete="off"
                    placeholder="请再次确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="submitPass">确定修改</el-button>
      </div>
    </el-dialog>

    <!-- 修改手机号 -->
    <el-dialog title="修改手机号"
               :visible.sync="dialogFormVisible2"
               width="593px"
               height="376px">
      <el-form :model="phoneForm"
               status-icon
               :rules="phoneRule"
               ref="phoneForm"
               class="demo-ruleForm">
        <el-form-item prop="phonenumber">
          <el-input v-model.trim="phoneForm.phonenumber"
                    type="text"
                    @input="phonechange"
                    placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="phoneForm.code"
                    placeholder="验证码"
                    style="width: 63%">
          </el-input>
          <el-button :class="phonestate?'bgcolor':'bgcolor stop'"
                     :disabled="!phonestate"
                     v-if="!countdown"
                     @click="getCodeData">
            {{countdown1?"重新发送":"获取验证码"}}
          </el-button>

          <el-button class="bgcolor stop"
                     v-if="countdown"
                     :disabled="true">
            {{countdown}} s
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button :disabled="!phonestate"
                   :class="phonestate?'bgcolor':'bgcolor stop'"
                   @click="submitPhone">确定修改</el-button>
      </div>
    </el-dialog>

    <!-- 修改邮箱 -->
    <el-dialog title="绑定/修改邮箱"
               :visible.sync="dialogFormVisible3"
               width="593px"
               height="376px">
      <el-form :model="emailForm"
               status-icon
               :rules="emailRule"
               ref="emailForm"
               class="demo-ruleForm">
        <el-form-item prop="email">
          <el-input type="email"
                    v-model="emailForm.email"
                    placeholder="请输入邮箱"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input type="password"
                    v-model="emailForm.pass"
                    autocomplete="off"
                    placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input type="password"
                    v-model="emailForm.checkPass"
                    autocomplete="off"
                    placeholder="请再次确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="submitEmail">确定绑定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userAvatar from "./userAvatar";
import userInfo from "./userInfo";
import { getUserProfile, updateUserPwd } from "@/api/system/user";
import { isRegister, getCode } from '@/api/register'
import { resetUserPwd, updatePhone } from "@/api/system/custom";

export default {
  name: "Profile",
  components: { userAvatar, userInfo, },
  data () {
    // 修改密码校验

    // 邮箱密码
    var validatePass4 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.emailForm.checkPass !== "") {
          this.$refs.emailForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass5 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.emailForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      phonestate: false,
      countdown: 0,
      countdown1: 0,
      emailcountdown: 0,
      emailcountdown1: 0,
      uuid: '',
      ruleForm: {
        pass: "",
        checkPass: "",
        oldPassword: "",
      },
      user: {},
      phoneForm: {
        phonenumber: "",
        code: "",
      },
      emailForm: {
        email: "",
        pass: "",
        checkPass: "",
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          }
        ],
        pass: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          }
        ],
        checkPass: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 8, max: 30, message: '密码长度在8到30个字符之间', trigger: 'blur' },
          // 正则表达式校验
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_])[a-zA-Z\d-_]+$/,
            message: '密码必须包含至少一位大小写字母、数字和符号（-、_）',
            trigger: 'blur'
          }
        ],
      },
      // 手机号校验
      phoneRule: {
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
        code: { required: true, message: "验证码不能为空", trigger: "blur" },
      },

      // 邮箱校验
      emailRule: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            pattern:
              /^([a-zA-Z]|[0-9])(\w|\-|\.)+@(([a-zA-Z0-9]|\-|\.)*([a-zA-Z0-9]|\-))+\.[a-zA-Z]{1,}$/,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        pass: [{ validator: validatePass4, trigger: "blur" }],
        checkPass: [{ validator: validatePass5, trigger: "blur" }],
      },
    };
  },
  created () {
    this.getUser();
  },
  methods: {
    submitPass () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          updateUserPwd(this.ruleForm.oldPassword, this.ruleForm.checkPass).then(response => {
            this.dialogFormVisible = false
            this.$modal.msgSuccess("修改成功");
          });
        }
      })
    },
    submitPhone () {
      if (!this.phonestate) {
        this.$message.error("请先输入正确的手机信息")
        return
      }
      var that = this;
      this.$refs.phoneForm.validate((valid) => {
        if (valid && that.phoneForm.code) {
          that.phoneForm.uuid = that.uuid;
          if (that.uuid) {
            const params = {
              userId: this.$store.getters.userId,
              ...that.phoneForm
            }
            updatePhone(params).then(res => {
              this.dialogFormVisible2 = false
              this.$modal.msgSuccess("修改成功");
              this.getUser();
            })
          } else {
            this.$message.warning("请先发送验证码在进行操作")
          }

        }
      })
    },
    phonechange () {
      let reg = /^1[3456789]\d{9}$/
      if (reg.test(this.phoneForm.phonenumber)) {
        this.phoneForm.registerType = 1
        isRegister(this.phoneForm).then(res => {
          if (res.code == '200' && res.data > 0) {
            this.phonestate = false
            this.$message.warning("该手机已注册，不可使用")
          } else {
            // this.$message.warning("您尚未注册账号，请通过“立即注册”按钮进行注册账号！")
            this.phonestate = true
          }
        })
      } else {
        this.phonestate = false
      }
    },
    getCodeData () {
      this.uuid = ''
      getCode(this.phoneForm).then(response => {
        if (response.code == "200") {
          this.uuid = response.msg;

          if (this.countdown === 0) {
            this.countdown = 60
            this.countdown1 = 120
            const timer = setInterval(() => {
              if (this.countdown > 0) {
                this.countdown--;
              } else {
                clearInterval(timer);
              }
            }, 1000);
            const timer1 = setInterval(() => {
              if (this.countdown1 > 0) {
                this.countdown1--;
              } else {
                clearInterval(timer1);
              }
            }, 1000);
          }
        }
      })
    },
    // 修改邮箱
    submitEmail () {
      this.$refs.emailForm.validate((valid) => {
        if (valid) {
          this.emailForm.registerType = 2
          isRegister(this.emailForm).then(res => {
            if (res.code == '200' && res.data > 0) {
              this.phonestate = false
              this.$message.warning("该邮箱已注册，不可使用")
              return false;
            } else {
              this.emailForm.userId = this.user.userId;
              resetUserPwd(this.emailForm.userId, this.emailForm.pass).then(res => {
                this.dialogFormVisible3 = false
              })
              this.getUser();
            }
          })
        }
      })
    },
    // 退出
    async logout () {
      this.$confirm("确定注销并退出系统吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("LogOut").then(() => {
            location.href = "/index";
          });
        })
        .catch(() => { });
    },
    getUser () {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-person {
  height: 100%;
  // padding: 0 0 20px 0px;
  border-radius: 6px;
  box-sizing: border-box;
  background-color: #fff;
  .perbox {
    width: 100%;
    height: 300px;
    background: url("../../../../assets/images/user/user1.png") no-repeat;
    background-size: cover;
    padding: 5px;
    box-sizing: border-box;
    // margin-top: 20px;
    position: relative;
    h2 {
      font-size: 20px;
      // margin-top: 20px;
    }
  }

  .user-info {
    // width: 100%;
    // background: #fff;
    display: flex;
    align-items: center;
    // margin: 0 auto;
    position: absolute;
    left: 56px;
    top: 181px;
    right: 62px;
    .userbox {
      width: 100%;
      height: 210px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #ffffff;
      box-shadow: 0px 4px 12px 0px rgba(211, 211, 211, 0.25);
      border-radius: 6px 6px 6px 6px;
      padding: 50px 44px 44px 44px;
      margin-right: 30px;
    }
    .userphoto {
      width: 126px;
      height: 126px;
      background: #ffffff;
      opacity: 1;
      margin-right: 50px;
      img {
        width: 126px;
        height: 126px;
      }
    }
    .opinion {
      width: 100%;
      .username {
        display: flex;
        flex-direction: column;
        .lfna {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .left {
            display: flex;
            align-items: center;
            p {
              width: 66px;
              height: 29px;
              font-size: 22px;
              font-family: Microsoft YaHei-Bold, Microsoft YaHei;
              font-weight: bold;
              color: #222222;
              line-height: 26px;
            }
            span {
              display: block;
              width: 65px;
              height: 23px;
              text-align: center;
              color: #ffffff;
              background: #aa2290;
              border-radius: 4px 4px 4px 4px;
              margin-left: 25px;
            }
          }
        }
        .bottom {
          display: flex;
          flex-direction: column;
          p {
            font-size: 14px;
            font-weight: 400;
            color: #737382;
          }
        }
      }
    }
  }
  .botuser {
    height: 200px;
    display: flex;
    flex-direction: column;
    margin-top: 400px;
    margin-left: 200px;
    // margin-bottom: 20px;
    p {
      font-size: 16px;
      font-weight: 400;
      color: #848491;
      display: flex;
      span {
        display: block;
        color: #222222;
      }
    }

    .el-button {
      width: 102px;
      height: 43px;
      border: #aa2290;
      background: #aa2290;
      color: #ffffff;
    }
  }
  .el-dialog__wrapper {
    display: flex;
    align-items: center;
  }
  ::v-deep.el-dialog {
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
  }
  ::v-deep.el-dialog__body {
    padding: 0px 20px 0 20px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .el-form {
      width: 380px;
      margin-top: 30px;
      .el-input__inner {
        height: 44px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    padding: 0 0 20px 0;
    .el-button--medium {
      width: 380px;
      height: 44px;
      border: #aa2290;
      background: #aa2290;
      color: #ffffff;
    }
    .stop {
      background: #ccc;
    }
  }
  .bgcolor {
    width: 117px;
    height: 44px;
    background: #aa2290;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    float: right;
    padding: 9px 11px 7px;
    line-height: 1;
    border: none;
    color: #fff;
    cursor: pointer;
  }
  .stop {
    background: #ccc;
  }
}
</style>

